//即时编辑插件.
(function($){
    
    var $contentTmp = '<div class="content selectable" contentEditable="true">{0}</div>',
        saveBtnTmp = '<span class="inplaceEditorSaver {saveBtnCls}">Save</span>',
    
        //默认配置.
        defaultConfig = {
            mode : 'view',  //or 'edit',初始状态编辑模式.
            triggerMode : 'click',  //or 'dblclick'
            type : 'input',     //or 'textarea' / 'contentEditable'
            isShowSaveButton : true,    //是否显示保存按钮
            isComplexEditor : false,    //是否是复杂控件。如果容器中包括非编辑的功能性内容时，此容器的editInplace对象为复杂的.
            onSave : Function.empty,    //保存事件逻辑.
            editorCls : '',
            saveBtnCls : '',            
            tooltip : 'click to edit ...'  
        },
        /**
         * 创建输入框.
         */
        createEditorBox = function(editorBoxconfig){
            if(editorBoxconfig['type'] != 'contentEditable'){
                var $editorBox = $(editorBoxconfig['type'] === 'textarea' ? '<textarea></textarea>' : '<input />');                
                $editorBox.addClass('inplaceEditor');
                if(editorBoxconfig['editorCls']){
                    $editorBox.addClass(editorBoxconfig['editorCls']);
                }
                return $editorBox;
            }            
        },
        /**
         * 创建保存按钮.
         */
        createSaveBtn = function(isShowSaveButton, config){
            if(isShowSaveButton){
                return $(saveBtnTmp.format({ 
                    saveBtnCls : config['saveBtnCls'] })
                );
            }
        },        
        //提交编辑内容.
        submitNewText = function($editorBox, $saveBtn, config){
            var newText,
                $content = config['isComplexEditor'] ? this.find('.content') : this;
            
            //为空删除.
            if(config['isEmptyRemove'] && !$editorBox.val().trim()){
                $editorBox.closest('.stringListItem').remove();
                return false;
            }
            
            if($editorBox){
                newText = ( $editorBox.val().nl2br() || this.data('originalText') );
                $editorBox.remove();
                if($saveBtn){
                    $saveBtn.remove();
                }
                $content.html(newText);
            } else {                        
                newText = $content.html();                                                
            }
            
            this.removeClass('editing');                    
            config['onSave'].call(this, newText, this.data('originalText'));                    
        },
        registerHandler = function($editorBox, $saveBtn, config){
            var _this = this;            
            if(config['isShowSaveButton'] !== false){
                $saveBtn.on({
                    click : function(e) {
                        submitNewText.call(_this, $editorBox, $saveBtn, config);
                        e.stopPropagation();
                    },
                    dblclick : function(){ 
                        e.stopPropagation(); 
                    },
                });
            }                
            ($editorBox || _this).bind( {
                click : function(){
                    return false;    
                },
                dblclick : function(){ 
                    return false; 
                },
                keydown : function(e){
                    if(e.keyCode === 13 && ( config['type'] !== 'textarea' || e.ctrlKey ) ){                        
                        submitNewText.call(_this, $editorBox, $saveBtn, config);                                               
                    }                   
                },
                blur : function(e){                    
                    submitNewText.call(_this, $editorBox, $saveBtn, config);                    
                }, 
                contextmenu : function(e){ 
                    //在输入框中，启用浏览器默认的快捷菜单，便于用户拷贝与粘贴内容。
                    e.stopPropagation(); 
                }
            } );
        };
    
    //----------------------------------------------------------------------------------------------------------------
    
    /**
     * 注册即时编辑功能.
     * @method editInplace
     * @param config {Option}
     * @return jQuery
     */
    $.fn.editInplace = function(config) {
	    config = $.extend({}, defaultConfig, config);
	    	    	    
		$(this).each(function() {	
		    if($(this).hasClass('editInplace')){
		        return false;
		    }
    	    var $editInplace = $(this).addClass('editInplace');            
            //编辑提示.
            if(!$editInplace.html().trim()){
                $editInplace.html(config['tooltip']);
            }            
        	var $editorBox = createEditorBox({    //输入控件，若type=contentEditable,则null.
                    type : config['type'],
                    editorCls : config['editorCls']
                }),
                //保存按钮.
                $saveBtn = createSaveBtn(config['isShowSaveButton'] !== false, {
                    saveBtnCls : config['saveBtnCls']
                }),
                $content = $editInplace.find('.content');
             
            if($editorBox){    
    			//双击时.
    			$editInplace.bind(config['triggerMode'], function(e) {    			    
    			    if(config['isComplexEditor'] && !$editInplace.hasClass('editable')){
    			        return false;
    			    }    			    
    				if(!$editInplace.hasClass('.editing')) {
    				    $editInplace.removeClass('selected');    				    
    				    registerHandler.call($editInplace, $editorBox, $saveBtn, config);    				      				
        				$editInplace.addClass('editing');        				
        				$editInplace.data('originalText', $editInplace.html().br2nl());        				
        				if( config['isComplexEditor'] ){        				    
        				    if($content.length){
        				        $editInplace.data('originalText', $content.html().br2nl());
        				        $content.remove();
        				    } else {
        				        $editInplace.data('originalText', '');
        				    }
        				} else {
        				    $editInplace.html('');    				    
        				}     
        				var originalText = $editInplace.data('originalText');   				    						
    				    $editorBox.val( originalText == config['tooltip'] ? "" : originalText );
    				    $editInplace.append($editorBox);    				    				
        				if(config['isShowSaveButton'] !== false){
        				    $(this).append($saveBtn);    				    
        				}
        				$editorBox.focus();
    			    }
    				e.stopPropagation();
    			});
    			//启用编辑模式.
    			if(config['mode'] === 'edit') {
    				$editInplace.trigger(config['triggerMode']);
    			}
			} else {
			    if( config['isComplexEditor'] && !$content.length ){
                    $editInplace.append($($contentTmp.format('')));
                } else {
                    $content.addClass('selectable');
                    $content.attr('contentEditable', true);   
                }                
			    if(config['isComplexEditor'] && !$editInplace.hasClass('editable')){
                    $editInplace.find('.content').removeClass('selectable');
                }
			}
		});		
        return this;
	};
    /**
     * 注销即时编辑控件.
     * @method unregisterEditInplace
     * @return jQuery
     */
    $.fn.unregisterEditInplace = function(){		
		$(this).unbind('dblclick').unbind('click');	
		return this;
	};
})($);